from django.shortcuts import render
from django.http import HttpResponse
import re

class AdminLoginMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # 检测当前的请求是否已经登录,如果已经登录,.则放行,如果未登录,则跳转到登录页
        urllist = ['/myadmin/login','/myadmin/dologin','/myadmin/verifycode']
        # 判断是否进入了后台,并且不是进入登录页面
        # print(request.path)
        if re.match('/myadmin/',request.path) and request.path not in urllist:

            # 检测session中是否存在 adminlogin的数据记录
            if not request.session.get('AdminLogin',''):
                # 如果在session没有记录,则证明没有登录,跳转到登录页面
                return HttpResponse('<script>alert("请先登录");location.href="/myadmin/login";</script>')
        

        #判断是否进入网站前台的 首页,列表,详情,排除购物车, (个人中心,我的订单,下单,付款)
        urls=['/orderadd','/ordercreate','/buy','/myorder']
        if request.path in urls:
            if not request.session.get('VipUser',''):
                return HttpResponse('<script>alert("请先登录");location.href="/login";</script>')
        
        # 不作任何处理
        response = self.get_response(request)
        return response
